<template>
  <div class="common-table">
    <div class="table-item">
      <formItem title="名称" sub="*">
        <template v-slot:right>
          <el-input v-model="formObj.name" placeholder="请输入名称" type="text"/>
        </template>
      </formItem>
      <formItem title="位置" sub="*">
        <template v-slot:right>
          <el-input v-model="formObj.location" placeholder="请输入位置" type="text"/>
        </template>
      </formItem>
      <formItem title="面积" sub="*">
        <template v-slot:right>
          <el-input v-model="formObj.area" placeholder="请输入面积" type="text"/>
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <formItem title="区镇" sub="*">
        <template v-slot:right>
          <el-select v-model="formObj.town" popper-class="big-screnn-popper" placeholder="请选择区镇">
            <el-option
                v-for="item in cityOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
      <formItem title="类型" sub="*">
        <template v-slot:right>
          <el-select v-model="formObj.type" popper-class="big-screnn-popper" placeholder="请选择类型"

          >
            <el-option
                v-for="item in typeOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
      <formItem title="供地方式" sub="*">
        <template v-slot:right>
          <el-select
              v-model="formObj.methods"
              popper-class="big-screnn-popper"
              placeholder="请选择类型"
          >
            <el-option
                v-for="item in landTypeOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <formItem title="用途" sub="*">
        <template v-slot:right>
          <el-select v-model="value1" popper-class="big-screnn-popper" placeholder="请选择用途"
                     allow-create
                     clearable
                     filterable
                     multiple
                     collapse-tags
                     collapse-tags-tooltip
          >
            <el-option
                v-for="item in useOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
      <formItem title="申报时间" sub="*">
        <template v-slot:right>
          <el-date-picker
              v-model="formObj.reportTime"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </template>
      </formItem>
      <formItem title="计划踏勘时间" sub="*">
        <template v-slot:right>
          <el-date-picker
              v-model="formObj.planTime"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </template>
      </formItem>
      <!-- 为了保证space-between样式能完整生效，空的formitem需要加一个div放这里即可 -->
      <div class="empty-form-item"></div>
    </div>
    <div class="table-item">
      <formItem title="计划土壤检测时间" sub="*">
        <template v-slot:right>
          <el-date-picker
              v-model="formObj.testTime"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </template>
      </formItem>
      <formItem title="编号">
        <template v-slot:right>
          <el-input v-model="formObj.code" placeholder="请输入名称" type="text"/>
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <div class="table-full-text">
        <div class="left" v-if="formObj.fileName === ''">
          <span>数据导入</span>
        </div>
        <div class="right">
          <div class="red-line">
            <formItem title="数据导入" v-if="formObj.fileName !== ''">
              <template v-slot:right>
                <el-input v-model="formObj.fileName" placeholder="请输入名称" type="text"/>
              </template>
            </formItem>
            <el-upload
                action="api/analyseKMZ"
                :on-success="handleAvatarSuccess"
                method="post"
                :show-file-list="false"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
            <div style="margin-left: 10px">
              <el-button type="primary" @click="clear">取消上传</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import {reactive, defineComponent, watch, getCurrentInstance, onMounted, ref} from 'vue'
import formItem from "@/components/commonFomItem/index.vue";
import * as turf from "@turf/turf";
import {ElNotification, UploadProps} from "element-plus";
import Data from "../../../public/config/data.json"
export default defineComponent({
  components: {formItem},
  props: ['confirmState', 'index', 'PassState', 'newState'],
  emits: ['receiveStateId'],
  setup(props, context) {

        const instance = getCurrentInstance();
    const yjs = instance?.appContext.config.globalProperties.yjs;
    const Cesium = instance?.appContext.config.globalProperties.Cesium;
    const cityOption = reactive(Data).selectTown
    //用途
    const useOption = reactive(Data).useOption
    const landTypeOption = reactive(Data).landClass
    const typeOption = reactive(Data).type
    const formObj = reactive({
      name: '',
      location: '',
      area: '',
      town: '',
      type: '',
      use: '',
      methods: '',
      geom: '',
      reportTime: '',
      planTime: '',
      dataExport: '',
      testTime: '',
      code: '',
      code1:'',
      fileName:''
    })
    const value1 = ref([])
    //创建用途字段
    const createUse =()=>{
      formObj.use = ''
      for(let i =0;i<value1.value.length;i++){
        if(formObj.use === ''){
          formObj.use = value1.value[i]+ formObj.use
        }else {
          formObj.use = formObj.use +','+ value1.value[i]
        }
      }
    }
    //修改地块数据
    const change = () => {
      appContext.config.globalProperties.axios({
        url: `api/update/geom`,
        method: 'post',
        data: formObj,
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("landId", props.index);
          oMyForm.append("geom", formObj.geom);
          return oMyForm;
        }]
      }).then(() => {
        ElNotification({
          title: '修改地块数据',
          message: "修改成功",
          type: 'success',
          position: 'top-left',
          offset: 300,
        })
      })
    }

    //上传文件
    const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
      formObj.fileName = uploadFile.name
      formObj.geom = response
      console.log(response);

      ElNotification({
        title: '上传地块数据',
        message: "上传成功",
        type: 'success',
        position: 'top-left',
        offset: 300,
      })
    }

    //取消数据
    const clear = () => {
      formObj.fileName = ""
      formObj.geom = "";
      ElNotification({
        title: "取消上传数据",
        message: "取消成功",
        type: "success",
        position: "top-left",
        offset: 300,
      });
    };

    //确定键
    watch(() => props.confirmState, () => {
      createUse()
      pushData()
    })
    const pushData = () => {
      appContext.config.globalProperties.axios({
        url: `api/update/declare`,
        method: 'post',
        data: formObj,
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("landId", props.index);
          oMyForm.append("bz", formObj.name);
          oMyForm.append("landLoc", formObj.location);
          oMyForm.append("landArea", formObj.area);
          oMyForm.append("geom", formObj.geom);
          oMyForm.append("town", formObj.town);
          oMyForm.append("method", formObj.methods);//供地方式
          oMyForm.append("landType", formObj.use);//用途
          oMyForm.append("landClass", formObj.type);//类型
          oMyForm.append("reportTime", formObj.reportTime);
          oMyForm.append("planTime", formObj.planTime);
          oMyForm.append("testTime", formObj.testTime);
          oMyForm.append("methods", formObj.methods);
          return oMyForm;
        }]
      }).then(() => {

        let points = [];
          let str = formObj.geom;
          points = str.split(" ");
          let turfcoords = [];
          let degArray = [];
          for (let i = 1; i < points.length; i++) {
            let point = points[i].split(",");
            let turfpoint = [];
            turfpoint.push(point[0] * 1);
            turfpoint.push(point[1] * 1);
            degArray.push(point[0] * 1);
            degArray.push(point[1] * 1);
            turfcoords.push(turfpoint);
          }
          let _color = Cesium.Color.fromCssColorString("#D13939");
          var _entity = new Cesium.Entity({
            name: "land." + props.index,
            polyline: {
              positions: Cesium.Cartesian3.fromDegreesArray(degArray),
              width: 2.5,
              // arcType: Cesium.ArcType.NONE,
              material: _color,
              classificationType: Cesium.ClassificationType.BOTH,
            },
            polygon: {
              hierarchy: {
                positions: Cesium.Cartesian3.fromDegreesArray(degArray),
              },
              material: Cesium.Color.fromAlpha(_color, 0.5),
              classificationType: Cesium.ClassificationType.TERRAIN,
              outline: true, // height is required for outline to display
            },
          });

          var polygon = turf.polygon([turfcoords]);

          // var polygon = turf.polygon([turfcoords]);

          var center = turf.centerOfMass(polygon);

          var _pointEntity = new Cesium.Entity({
            name: "land." + props.index,
            position: Cesium.Cartesian3.fromDegrees(
                center.geometry.coordinates[0],
                center.geometry.coordinates[1],
                20
            ),
            billboard: {
              image: "img/step1.png",
              scale: 1,
              scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 40000, 0.5),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                  0.0,
                  60000
              ),
            },

            label: {
              text: formObj.name,
              font: "normal small-caps normal 30px 楷体",
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,

              fillColor: Cesium.Color.AZURE,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 20000, 0.5),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                  0.0,
                  20000
              ),
              pixelOffset: new Cesium.Cartesian2(0, -16),
            },
            popup: {
              html:
                  '<div class="divpoint divpoint-theme-29baf1" style="pointer-events:all;">' +
                  '<div class="divpoint-wrap">' +
                  '<div class="area">' +
                  '<img class="imagegb" src="public/img/marker/关闭.png" alt="">' +
                  '<div class="title">' +
                  formObj.name +
                  '</div><div class="label-content"><div class="data-li" style="padding:4px"><div class="data-label"  style="max-width: 200px;word-wrap: break-word;word-break: break-all;overflow: hidden;display: inline-block;white-space: normal;">' +
                  "行政区划：" + formObj.town + "</br>类型：" + formObj.use + "</br>规划用途：" + formObj.type + "</br>位置：" + formObj.location + "</br>面积：" + formObj.area + "亩</br>" +
                  '<button onclick="clickme()">时序浏览</button></br>' +
                  '<button onclick="toggleClick(' + props.index + ')">立体净地</button></br></div></div></div></div></div><div class="b-t-l"></div><div class="b-b-r"></div></div></div>',
            },
          });

          window.viewer.dataSources.getByName("myland")[0].entities.add(_entity);
          window.viewer.dataSources
              .getByName("mylandpoint")[0]
              .entities.add(_pointEntity);
          window.viewer
              .flyTo(_entity, {offset: new Cesium.HeadingPitchRange(0, -1, 1000)})
              .then(() => {
                yjs.util.highlightEntity(_entity, {
                  time: 5, //闪烁时长（秒）
                  maxAlpha: 1,
                  color: Cesium.Color.YELLOW,
                  onEnd: function () {
                    //结束后回调
                  },
                });
              });


        ElNotification({
          title: '修改数据',
          message: "修改成功",
          type: 'success',
          position: 'top-left',
          offset: 300,
        })
      })
    }


    //通过键
    watch(() => props.PassState, () => {
      createUse()
      passData()
    })
    const passData = () => {
      appContext.config.globalProperties.axios({
        url: `api/pass/declare`,
        method: 'post',
        data: formObj,
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("landId", props.index);
          oMyForm.append("bz", formObj.name);
          oMyForm.append("landLoc", formObj.location);
          oMyForm.append("geom", formObj.geom);
          oMyForm.append("landArea", formObj.area);
          oMyForm.append("town", formObj.town);
          oMyForm.append("method", formObj.methods);//供地方式
          oMyForm.append("landType", formObj.use);//用途
          oMyForm.append("landClass", formObj.type);//类型
          oMyForm.append("reportTime", formObj.reportTime);
          oMyForm.append("planTime", formObj.planTime);
          oMyForm.append("testTime", formObj.testTime);
          oMyForm.append("methods", formObj.methods);
          return oMyForm;
        }]
      }).then(() => {
        console.log("passOK")
      })
    }
    const {appContext} = getCurrentInstance();
    //初始化
    const init = () => {
      appContext.config.globalProperties.axios.post(`api/landSearch/${props.index}`).then((response) => {
        response.data.forEach(item => {
          formObj.use = item.landType
          formObj.name = item.bz
          formObj.town = item.town
          formObj.location = item.landLoc
          formObj.area = item.landArea
          formObj.type = item.type
          formObj.methods = item.methods
          value1.value = item.landType.split(',')
          let data = new Date()
          let year = data.getFullYear().toString()
          for (let i = 0; i < cityOption.length; i++) {
            if (formObj.town === cityOption[i].value) {
              formObj.code = year + '02' + '0' +(i + 1).toString()
            }
          }
          if(props.index <10)
          {
            formObj.code =  formObj.code + '00'+props.index
          }else if(props.index > 99){
            formObj.code = formObj.code  +props.index
          }else {
            formObj.code = formObj.code  + '0'+props.index
          }
        })
      })
      appContext.config.globalProperties.axios.post(`api/findDeclare/${props.index}`).then((response) => {
        response.data.forEach(item => {
          formObj.reportTime = item.reportTime
          formObj.planTime = item.planTime
          formObj.testTime = item.testTime
        })
      })
    }
    watch(() => props.newState, () => {
      init()
    })
    onMounted(() => {
      init()

    })
    return {
      cityOption,
      typeOption,
      useOption,
      formObj,
      pushData,
      passData,
      handleAvatarSuccess,
      change,
      landTypeOption,
      init,
      value1,
      createUse,
      clear
    }
  }
})

</script>


<style scoped lang="scss">
.common-table {
  .table-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    color: #FFFFFF;

    .table-full-text {
      display: flex;
      width: 100%;
      align-items: center;

      .left {
        color: rgba(240, 245, 255, 0.95);
        padding-right: 10px;
        width: 61px;
      }

      .right {
        flex: 1;

        .red-line {
          display: flex;
          //align-items: center;
          .red-line-text {
            padding-right: 12px;
            color: #e9e9e9;
          }
        }
      }
    }
  }

  .empty-form-item {
    width: 280px;
  }

  .tips-text {
    margin-left: 62px;
    margin-top: -16px;
    color: #e9e9e9;
  }
}
</style>
